import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/foundation.dart';
import 'package:s_mankey/config/resource_mananger.dart';
import 'package:s_mankey/model/user_model.dart';
import 'api.dart';
import '../storage_manager.dart';

final Http1 http1 = Http1();

class Http1 extends BaseHttp {
  @override
  void init() {

    options.baseUrl = 'https://api.in-monkeys.com/api/v1/'; //正式
//    options.baseUrl = 'http://api.in-monkeys.com/api/v1/'; //测试

    interceptors
      ..add(ApiInterceptor())
    // cookie持久化 异步
      ..add(CookieManager(
          PersistCookieJar(dir: StorageManager.temporaryDirectory.path)));
  }
}

/// 盛猴子 UI API
class ApiInterceptor extends InterceptorsWrapper {
  @override
  onRequest(RequestOptions options) async {
    debugPrint('---api-request--->url--> ${options.baseUrl}${options.path}' +
        ' queryParameters: ${options.queryParameters}');
    UserModel userModel = StorageManager.localeStorage.getItem(AppGlobalConfig.USERINFO);
    options.headers = {'token': userModel.accessToken?? ''};
//    debugPrint('---api-request--->data--->${options.data}');
    return options;
  }

  @override
  onResponse(Response response) {
    debugPrint('---api-response--->resp----->${response.data}');
    ResponseData respData = ResponseData.fromJson(response.data);

    //请求成功
    if (respData.success) {
      response.data = respData;
      return http1.resolve(response);
    }

    //请求失败
    if (!respData.success) {
      if(respData.code == -1001){
        // 如果cookie过期,需要清除本地存储的登录信息
        // StorageManager.localStorage.deleteItem(UserModel.keyUser);
      }
//      return http.resolve(respData.message);
      ///抛出异常
      throw NotSuccessException.fromRespData(respData);
    }

  }
}



class ResponseData extends BaseResponseData {

  bool get success => 0 == code;

  ResponseData.fromJson(Map<String, dynamic> json) {
    code = json['code'];
    message = json['message'];
    data = json['data'];
  }
}
